package utils;

import pers.cz.common.exception.BusinessException;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Date;

/**
 * @program: Jef-orm
 * @description: 反射工具
 * @author: Cheng Zhi
 * @create: 2023-09-07 16:49
 **/
public class ReflectUtils {

    public static Object typeTransform(Field field, String value) {

        Type genericType = field.getGenericType();
        int index = value.indexOf("."); // 检查是否包含小数点，excel中如果是小数点要截取
        switch (genericType.getTypeName()) {
            case "java.lang.Integer":
                return Integer.valueOf(value.substring(0, index == -1 ? value.length() : index));
            case "int":
                return Integer.valueOf(value.substring(0, index == -1 ? value.length() : index));
            case "java.lang.Long":
                return Long.valueOf(value.substring(0, index == -1 ? value.length() : index));
            case "long":
                return Long.valueOf(value.substring(0, index == -1 ? value.length() : index));
            case "java.lang.Float":
                return Float.valueOf(value);
            case "float":
                return Float.valueOf(value);
            case "java.lang.Double":
                return Double.valueOf(value);
            case "double":
                return Double.valueOf(value);
            case "java.lang.String":
                return value;
            case "java.util.Date":
                return DateUtils.strToDate(value);
            default:
                throw new IllegalArgumentException("参数类型错误");
        }

    }

    /**
     * 反射获取对象
     * @param clz
     * @param <T>
     * @return
     */
    public final static <T> T newInstance(Class<T> clz){
        try {
            return clz.newInstance();
        } catch (IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
            throw new IllegalStateException(e.getCause());
        }
    }
}
